<template>
  <div>
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAdd">新增点位</el-button>
        </div>
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="500px"
              :data="tableData"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
          >
            <el-table-column prop="id" label="ID" width="60"/>
            <el-table-column prop="name" label="点位名称" width="150" show-overflow-tooltip/>
            <el-table-column prop="latitude" label="纬度" width="100">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  @click="previewLocation(scope.row.latitude, scope.row.longitude, scope.row.name)"
                  :title="`点击查看 ${scope.row.name} 在地图上的位置`"
                >
                  {{ scope.row.latitude }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度" width="100">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  @click="previewLocation(scope.row.latitude, scope.row.longitude, scope.row.name)"
                  :title="`点击查看 ${scope.row.name} 在地图上的位置`"
                >
                  {{ scope.row.longitude }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="icon" label="图标" width="120">
              <template slot-scope="scope">
                <el-image
                    v-if="scope.row.icon"
                    :preview-src-list="[scope.row.icon]"
                    style="width: 60px; height: 60px"
                    :src="scope.row.icon" fit="contain">
                </el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="二维码" width="120">
              <template slot-scope="scope">
                <div class="qr-code-container">
                  <img 
                  style="display: none;"
                    :ref="`qrImage${scope.row.id}`"
                    :id="`qrImage${scope.row.id}`"
                    class="qr-code-image"
                    @click="previewQRCode(scope.row.id)"
                    :title="`点击预览 ${scope.row.name} 的二维码`"
                  />
                  <el-button type="text" @click="previewQRCode(scope.row.id)">预览二维码</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="160">
              <template slot-scope="scope">
                {{ scope.row.create_time ? new Date(scope.row.create_time).toLocaleString() : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </div>
    <Add ref="addFormRef" @get-page="initData" />
  </div>
</template>
<script>

import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add";
import QRCode from 'qrcode';

export default {
  name: "PointIndex",
  components: {
    Add
  },
  mixins: [crud],
  data() {
    return {
      request: http.point,
      searchList: [
        {
          label: '点位名称',
          prop: 'name',
          name: 'input',
          placeholder: '请输入点位名称'
        },
        {
          label: '内容描述',
          prop: 'content',
          name: 'input',
          placeholder: '请输入内容描述'
        }
      ],
      searchParams: {
        name: '',
        content: ''
      },
      defaultParams: {
        name: '',
        content: ''
      },
      tableData: []
    }
  },
  mounted() {
    // 监听数据变化，自动生成二维码
    this.$watch('tableData', (newData) => {
      if (newData && newData.length > 0) {
        this.$nextTick(() => {
          newData.forEach(item => {
            this.generateQRCode(item.id);
          });
        });
      }
    }, { immediate: true });
  },
  methods: {
    previewLocation(latitude, longitude, name) {
      // 使用百度地图或高德地图API预览位置
      const url = `https://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${encodeURIComponent(name)}&content=${encodeURIComponent(name)}&output=html&src=webapp.baidu.openAPIdemo`;
      window.open(url, '_blank');
    },
    
    // 生成二维码
    async generateQRCode(id) {
      const url = `http://map_h5.diandian.work/#/pages/map/index?id=${id}`;
      const img = this.$refs[`qrImage${id}`];
      
      if (!img) return;
      
      try {
        // 使用 qrcode 库生成二维码
        const qrDataURL = await QRCode.toDataURL(url, {
          width: 80,
          margin: 1,
          color: {
            dark: '#000000',
            light: '#FFFFFF'
          }
        });
        img.src = qrDataURL;
      } catch (error) {
        console.error('二维码生成失败:', error);
        // 如果生成失败，显示默认图片
        img.src = '';
      }
    },
    
    // 预览二维码
    previewQRCode(id) {
      const url = `http://map_h5.diandian.work/#/pages/map/index?id=${id}`;
      const img = this.$refs[`qrImage${id}`];
      
      if (img && img.src) {
        // 获取点位名称用于下载文件名
        const pointData = this.tableData.find(item => item.id === id);
        const fileName = pointData ? pointData.name : `point_${id}`;
        
        // 创建大图预览
        const h = this.$createElement;
        this.$msgbox({
          title: '二维码预览',
          message: h('div', { style: 'text-align: center;' }, [
            h('img', {
              attrs: {
                src: img.src,
                style: 'width: 200px; height: 200px; border: 1px solid #ddd; border-radius: 4px;'
              }
            }),
            h('p', { style: 'margin-top: 10px; color: #666;' }, `链接地址: ${url}`),
            h('div', { style: 'margin-top: 15px;' }, [
              h('el-button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  icon: 'el-icon-download'
                },
                on: {
                  click: () => this.downloadQRCode(img.src, fileName)
                }
              }, '下载二维码')
            ])
          ]),
          showCancelButton: false,
          showConfirmButton: false,
          customClass: 'qr-preview-dialog'
        });
      } else {
        this.$message.warning('二维码尚未生成，请稍后再试');
      }
    },
    
    // 下载二维码
    downloadQRCode(imageSrc, fileName) {
      // 显示加载提示
      const loading = this.$loading({
        lock: true,
        text: '正在准备下载...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 创建一个canvas来确保图片格式正确
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        
        img.crossOrigin = 'anonymous';
        img.onload = () => {
          // 设置canvas尺寸
          canvas.width = img.width;
          canvas.height = img.height;
          
          // 绘制图片到canvas
          ctx.drawImage(img, 0, 0);
          
          // 转换为blob并下载
          canvas.toBlob((blob) => {
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `${fileName}_二维码.png`;
            
            // 添加到DOM中并触发点击
            document.body.appendChild(link);
            link.click();
            
            // 清理DOM和URL
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            // 关闭加载提示
            loading.close();
            this.$message.success(`二维码下载成功：${fileName}_二维码.png`);
          }, 'image/png');
        };
        
        img.onerror = () => {
          loading.close();
          this.$message.error('图片加载失败，无法下载');
        };
        
        img.src = imageSrc;
        
      } catch (error) {
        loading.close();
        console.error('下载失败:', error);
        this.$message.error('下载失败，请重试');
      }
    }
  }
}
</script>

<style scoped lang="scss">
.table-layout {
  margin-top: 20px;
}
.table-handle {
  margin-bottom: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}

// 坐标按钮样式
.el-button--text {
  color: #409EFF;
  &:hover {
    color: #66b1ff;
  }
}

// 图标预览样式
.el-image {
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

// 二维码样式
.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  
  .qr-code-image {
    width: 80px;
    height: 80px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }
}

// 二维码预览弹窗样式
:deep(.qr-preview-dialog) {
  .el-message-box__message {
    text-align: center;
    
    .el-button {
      margin-top: 10px;
    }
  }
  
  .el-message-box__header {
    padding-bottom: 15px;
  }
  
  .el-message-box__content {
    padding: 20px;
  }
}
</style>
